package com.monster.servlet.user;

import com.monster.service.UserServiceImpl;
import com.monster.util.UserMessageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user/code_login")
public class CodeLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String phone = request.getParameter("phone");
        UserServiceImpl usi = new UserServiceImpl();
        Long userId = null;
        String message = null;
        if ((userId = usi.isRegistered(phone)) != null) {
            String smsCode = UserMessageUtil.getRandomCode();
            String smsText = "您正在登录本站，本次验证码为:"+smsCode+"，有效时间为5分钟，如非本人操作，请忽略此信息。";
            UserMessageUtil.sendMessage(phone, smsText);
            Map<String, Date> smsCodes = new HashMap<>();
            smsCodes.put(smsCode, new Date());
            request.getSession().setAttribute("smsCode", smsCodes);
            request.getSession().setAttribute("code_user_id", userId);
            message = "send";
            System.out.println(smsText);
        } else {
            message = "该手机号未注册！";
        }
        PrintWriter out = response.getWriter();
        out.print(message);
        out.flush();
        out.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }


}
